package com.solution.pc.home.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.solution.admin.auth.entity.UserEntity;
import com.solution.admin.auth.service.UserService;
import com.solution.admin.coupon.service.CouponGetService;
import com.solution.admin.home.constants.IndexConstants;
import com.solution.admin.home.entity.ModuleAndConfigEntity;
import com.solution.admin.home.entity.SiteConfigItemEntity;
import com.solution.admin.home.entity.SiteModuleEntity;
import com.solution.admin.home.service.IndexService;
import com.solution.admin.home.service.SiteModuleService;
import com.solution.admin.order.constants.OrderConstants;
import com.solution.admin.order.service.OrderService;
import com.solution.admin.product.entity.ProductBrandEntity;
import com.solution.admin.product.entity.ProductCategoryEntity;
import com.solution.admin.product.entity.ProductEntity;
import com.solution.admin.product.service.ProductCategoryBrandService;
import com.solution.admin.product.service.ProductCategoryService;
import com.solution.admin.product.service.ProductService;
import com.solution.admin.settings.entity.KeyMapEntity;
import com.solution.admin.settings.service.KeyMapService;
import com.solution.common.controller.BaseController;
import com.solution.common.utils.DateUtils;
import com.solution.common.utils.string.StringUtil;
import com.solution.pc.order.entity.CustomerOrderStatisticsEntity;

/**
 * 网站首页控制层
 * 首页分为几个模块：
 * 
 * 0、搜索关键字加载（ 携带个人信息）
 * 1、左侧菜单加载
 * 2、巨幕滚动广告加载
 * 3、右侧个人信息加载
 * 4、楼层  
 * 4.1、热品采购模块加载
 * 4.2、新品上市
 * 4.3、商品电脑
 * 5、品牌馆
 * 6、网站指南信息加载
 * 
 * （以上数据均从redis 缓存中加载）
 * 
 * @author llp
 * @date 2017-09-26 14:44:49
 */
@RequestMapping("/pc")
@Controller
public class IndexController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(IndexController.class);

	@Autowired
	private SiteModuleService siteModuleService;
	
	@Autowired
	private IndexService indexService;
	
	@Autowired
	private ProductCategoryService productCategoryService;
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private KeyMapService keyMapService;
	
	@Autowired
	private ProductService productService;
	
	@Autowired
	UserService userService;
	
	@Autowired
	ProductCategoryBrandService productCategoryBrandService;
	
	@Autowired
	private CouponGetService couponGetService;
	
	/**
	 * 跳转网站首页
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author llp
 	 * @date 2017-09-26 14:44:49
	 */
	@RequestMapping("/index")
	public String toListSiteModulePage(HttpServletRequest request) {
		
		Map<String, Object> param = new HashMap<String, Object>();
		// 查询商品类型
		List<ProductCategoryEntity> categoryList = productCategoryService.listProductCategoryForIndex(param);
		if(categoryList !=null && categoryList.size() > 0){
			for (ProductCategoryEntity category : categoryList) {
				// 获取此父级分类下所有 子分类对应的品牌列表
				List<ProductBrandEntity> subBrandList = productCategoryBrandService.getSubBrandList(category.getId());
				category.setSubBrandList(subBrandList);
				
				if(StringUtil.isNotEmpty(category.getSubCategoryListStr())){
					List<ProductCategoryEntity> tmpCategoryList = JSONArray.parseArray("["+category.getSubCategoryListStr()+"]", ProductCategoryEntity.class);
					category.setSubCategoryList(tmpCategoryList);
				}
			}
		}
		request.setAttribute("categoryList", categoryList);
		
		// 楼层信息
		// 查询网站模块信息
		param.put("key", IndexConstants.REDIS_KEY_EB_SITE_MODULE_LIST);
		Map<String, SiteModuleEntity> smMap = indexService.listSiteModule(param);
		
		List<ModuleAndConfigEntity>  floorResultList = new ArrayList<ModuleAndConfigEntity>(); 
		Map<String, List<SiteConfigItemEntity>>  scMap = null;
		try {
			param.put("key", IndexConstants.REDIS_KEY_EB_INDEX_PRODUCT_FLOOR);
			// 从redis 中查询楼层配置信息
			scMap = indexService.listIndexProductFloor(param);
			
			if(scMap != null && scMap.size() > 0){
				for(Map.Entry<String, List<SiteConfigItemEntity>>  entry : scMap.entrySet()){
					ModuleAndConfigEntity  fie = new ModuleAndConfigEntity(smMap.get(entry.getKey()),entry.getValue());
					List<SiteConfigItemEntity>  itemList = entry.getValue();
					// 过滤掉已下架和删除的商品
					List<Long> productIdList = new ArrayList<Long>();
					if(itemList != null && itemList.size() > 0){
						for (SiteConfigItemEntity config : itemList) {
							if(StringUtil.isNotEmpty(config.getProductCode())){
								String[] tmpArr = config.getProductCode().split("##");
								productIdList.add(Long.parseLong(tmpArr[0]));
								config.setProductId(tmpArr[0]);
							}
						}
					}
					
					List<SiteConfigItemEntity> tmpItemList = new ArrayList<SiteConfigItemEntity>();
					if(productIdList.size() > 0){
						param.clear();
						param.put("productIdList", productIdList);
						param.put("isLogin", isLogin(request)?"1":"0");
						param.put("customerLevel", getCustomerLevel());
						List<ProductEntity> productList = productService.listIndexFloorProduct(param);
						Map<Long, ProductEntity> productMap = new HashMap<Long, ProductEntity>();
						if(productList != null && productList.size() > 0){
							for (ProductEntity product : productList) {
								productMap.put(product.getId(), product);
							}
						}
						
						if(itemList != null && itemList.size() > 0){
							for (SiteConfigItemEntity config : itemList) {
								if(StringUtil.isNotEmpty(config.getProductId()) && productMap.containsKey(Long.parseLong(config.getProductId()))){
									ProductEntity product = productMap.get(Long.parseLong(config.getProductId()));
									config.setImagePath(product.getMainImagePath());
									config.setProductName(product.getProductName());
									tmpItemList.add(config);
								}
							}
						}
					}
					fie.setSiteModule(smMap.get(entry.getKey()));
					fie.setConfigItemList(tmpItemList);
					floorResultList.add(fie);
				}
			}
			if(floorResultList != null && floorResultList.size() > 0){
				Collections.sort(floorResultList, new Comparator<ModuleAndConfigEntity>() {
					public int compare(ModuleAndConfigEntity o1,
							ModuleAndConfigEntity o2) {
						return o1.getSiteModule().getId().compareTo(o2.getSiteModule().getId());
					}
				});
			}
			request.setAttribute("floorList", floorResultList);
			
		} catch (Exception e) {
			e.printStackTrace();
			handleException("查询首页楼层信息", logger, e);
		}
		
		
		// 品牌馆
		List<SiteConfigItemEntity>  pcList = null;
		try {
			param.put("key", IndexConstants.REDIS_KEY_EB_INDEX_BRAND_LIBRARY);
			pcList = indexService.listIndexBrandLibrary(param);
			request.setAttribute("brandList", pcList);
		} catch (Exception e) {
			handleException("查询首页品牌馆信息失败", logger, e);
		}
		
		// 查询品牌馆内容
		List<SiteConfigItemEntity>  brandList = null;
		try {
			param.put("key", IndexConstants.REDIS_KEY_EB_INDEX_BRAND_LIBRARY);
			brandList = indexService.listIndexBrandLibrary(param);
			request.setAttribute("brandList", brandList);
		} catch (Exception e) {
			handleException("查询首页品牌馆信息失败", logger, e);
		}
		
		// 查询积分商城、报价单入口
		List<SiteConfigItemEntity>  entryList = null;
		
		//签到控制,是否允许签到 1 允许,其他 禁止
		List<KeyMapEntity> signInControlList = keyMapService.listKeyMap("signInControl");
		if (null != signInControlList && signInControlList.size() != 0) {
			KeyMapEntity signInControl = signInControlList.get(0);
			if ("1".equals(signInControl.getKeyValue())) {
				request.setAttribute("signInControl", signInControl.getKeyValue());
			} else {
				request.setAttribute("signInControl", "0");
			}
		}
		try {
			param.put("key", IndexConstants.REDIS_KEY_EB_INDEX_SITE_ENTRY);
			entryList = indexService.listIndexBrandLibrary(param);
			request.getSession().setAttribute("entryList", entryList);
		} catch (Exception e) {
			handleException("查询首页积分商城、报价单入口失败", logger, e);
		}
		try {
			UserEntity user = userService.getUserById(getUserId());
			request.setAttribute("user", user);
			//查询是否有新的个人优惠券
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("isExp", "0");
			paramMap.put("customerId", getCustomerId());
			paramMap.put("notice", 0);
			int newCouponGetNum = couponGetService.countUserCouponGet(paramMap);
			request.setAttribute("newCouponGetNum", newCouponGetNum);
			if (newCouponGetNum > 0) {
				couponGetService.updateCouponNotice(paramMap);
			}
        } catch (Exception e) {
        	logger.error("没登录！");
        }
		
		return "pc/home/index";
	}
	
	/**
	 * 根据父级分类ID、品牌编码，获取对应二级分类列表
	 * 
	 * @param request
	 * @param parentCategoryId
	 * @param brandCodeStr
	 * @return List<ProductCategoryEntity>
	 * @author xu_cc
	 * @throws Exception
	 *             exception
	 * @Date 创建时间：2018年3月5日 下午4:52:44
	 */
	@RequestMapping("getCategoryList")
	@ResponseBody
	@SuppressWarnings("unchecked")
	public List<ProductCategoryEntity> getCategoryList(HttpServletRequest request, Long parentCategoryId, String brandCodeStr) {
		try {
			if (null != parentCategoryId) {
				if (StringUtil.isNotNull(brandCodeStr)) {
					String[] brandCodeArr = brandCodeStr.split(",");
					List<ProductCategoryEntity> categoryList = new ArrayList<ProductCategoryEntity>();
					for (int i = 0; i < brandCodeArr.length; i++) {
						if (StringUtil.isNotNull(brandCodeArr[i])) {
							List<ProductCategoryEntity> subCategoryList = productCategoryBrandService.getSubCategoryList(parentCategoryId,
							        brandCodeArr[i]);
							if (null != subCategoryList && subCategoryList.size() > 0) {
								categoryList.addAll(subCategoryList);
							}
						}
					}
					// 去重
					List<ProductCategoryEntity> resultCategoryList = new ArrayList<ProductCategoryEntity>();
					Set<Long> proCategoryIdSet = new HashSet<Long>();
					for (ProductCategoryEntity category : categoryList) {
						if (!proCategoryIdSet.contains(category.getId())) {
							resultCategoryList.add(category);
							proCategoryIdSet.add(category.getId());
						}
					}
					return resultCategoryList;
				} else {
					Map<String, Object> param = new HashMap<String, Object>();
					param.put("parentCategoryId", parentCategoryId);
					return productCategoryService.listProductCategory(param);
				}
			} else {
				return Collections.EMPTY_LIST;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return Collections.EMPTY_LIST;
		}
	}

	/**
	 * 查询首页主屏幕广告图片信息 （查询redis）
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author llp
 	 * @date 2017-09-26 14:44:49
	 */
	@RequestMapping("/listIndexRollingAD")
	@ResponseBody
	public List<SiteConfigItemEntity> listIndexRollingAD(HttpServletRequest request){
		List<SiteConfigItemEntity>  sciList = null;
		try {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("key", IndexConstants.REDIS_KEY_EB_INDEX_AD);
			sciList = indexService.listIndexRollingAD(param);
		} catch (Exception e) {
			handleException("查询主屏幕广告图片信息失败", logger, e);
		}
		return sciList;
	}

	/**
	 * 查询首页商品类型 （查询redis）
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author llp
 	 * @date 2017-09-26 14:44:49
	 */
	@RequestMapping("/listIndexProductCategory")
	@ResponseBody
	public List<ProductCategoryEntity> listIndexProductCategory(HttpServletRequest request){
		List<ProductCategoryEntity>  pcList = null;
		try {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("key", IndexConstants.REDIS_KEY_EB_INDEX_PRODUCT_CATEGORY);
			pcList = indexService.listIndexProductCategory(param);
		} catch (Exception e) {
			handleException("查询首页商品类型", logger, e);
		}
		return pcList;
	}
	
	
	/**
	 * 查询热门搜索词
	 * @param request
	 * @return
	 */
	@RequestMapping("/listHotSearchKey")
	@ResponseBody
	public List<KeyMapEntity> listHotSearchKey(HttpServletRequest request){
		List<KeyMapEntity>  kmList = null;
		try {
			kmList = keyMapService.listKeyMap("hotSearchKey");
		} catch (Exception e) {
			handleException("查询热门搜索词", logger, e);
		}
		return kmList;
	} 
	
	/**
	 * 查询首页底部指南信息
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author llp
 	 * @date 2017-09-26 14:44:49
	 */
	@RequestMapping("/footer")
	@ResponseBody
	public Map<String, List<SiteConfigItemEntity>> listIndexFingerPost(HttpServletRequest request){
		Map<String, List<SiteConfigItemEntity>> resultMap = new HashMap<String, List<SiteConfigItemEntity>>();
		// 网站指南
		Map<String, Object> param = new HashMap<String, Object>();
		Map<String, List<SiteConfigItemEntity>> sccMap = null;
		try {
			// 查询网站指南类信息
			param.put("key", IndexConstants.REDIS_KEY_EB_INDEX_FINGER_POST);
			sccMap = indexService.listIndexFingerPost(param);
			resultMap.put("qaList",sccMap.get(IndexConstants.DB_KEY_SITE_CONFIG_FINGER_QA));
			resultMap.put("shoppingList", sccMap.get(IndexConstants.DB_KEY_SITE_CONFIG_FGINER_SHOPPING));
			resultMap.put("deliveryList", sccMap.get(IndexConstants.DB_KEY_SITE_CONFIG_FGINER_DELIVERY));
			resultMap.put("payTypeList", sccMap.get(IndexConstants.DB_KEY_SITE_CONFIG_FGINER_PAY_TYPE));
			resultMap.put("afterSalesList", sccMap.get(IndexConstants.DB_KEY_SITE_CONFIG_FGINER_AFTER_SALES));
			
		} catch (Exception e) {
			handleException("查询网站指南失败", logger, e);
		}
		return resultMap;
	}
	
	
	
	/**
	 * 查询客户的本周、本月订货情况
	 * @param request
	 * @return
	 */
	@RequestMapping("/listCustomerOrderStatistics")
	@ResponseBody
	public Map<String, String> listCustomerOrderStatistics(HttpServletRequest request){
		Map<String, String> resultMap = new HashMap<String, String>();
		if(!isLogin(request)){
			resultMap.put("TO_PAY_NUM", "0");
			resultMap.put("TO_SEND_NUM", "0");
			resultMap.put("TO_RECEIVE_NUM", "0");
			resultMap.put("OVERDUED_NUM", "0");
			resultMap.put("CUR_WEEK_NUM", "0");
			resultMap.put("CUR_MONTH_NUM", "0");
		}else{
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("customerId", getCustomerId());
			param.put("curWeekStartTime", DateUtils.getCurWeek());
			param.put("curMonthStartTime", DateUtils.getCurMonth());
			param.put("companyId", getCompany().getId());
			List<CustomerOrderStatisticsEntity> cosList = orderService.listCustomerOrderStatistics(param);
			Map<String, String> tmpMap = new HashMap<String, String>();
			if(cosList != null && cosList.size() > 0){
				for (CustomerOrderStatisticsEntity order : cosList) {
					tmpMap.put(order.getOrderStatus(), order.getOrderNum());
				}
			}
			
			
			String toPayNum = tmpMap.get(OrderConstants.ORDER_STATUS.WAIT_TO_PAY.getCode());
			String toSendNum = tmpMap.get(OrderConstants.ORDER_STATUS.WAIT_TO_SEND.getCode());
			String toReciveNum = tmpMap.get(OrderConstants.ORDER_STATUS.WAIT_TO_RECEIVE.getCode());
			String overduedNum = tmpMap.get("OVERDUED_NUM");
			String curWeekNum = tmpMap.get("CUR_WEEK_NUM");
			String curMonthNum = tmpMap.get("CUR_MONTH_NUM");
			
			resultMap.put("TO_PAY_NUM", StringUtil.isNotEmpty(toPayNum)?toPayNum:"0");
			resultMap.put("TO_SEND_NUM", StringUtil.isNotEmpty(toSendNum)?toSendNum:"0");
			resultMap.put("TO_RECEIVE_NUM", StringUtil.isNotEmpty(toReciveNum)?toReciveNum:"0");
			resultMap.put("OVERDUED_NUM", StringUtil.isNotEmpty(overduedNum)?overduedNum:"0");
			resultMap.put("CUR_WEEK_NUM", StringUtil.isNotEmpty(curWeekNum)?curWeekNum:"0");
			resultMap.put("CUR_MONTH_NUM", StringUtil.isNotEmpty(curMonthNum)?curMonthNum:"0");
		}
		
		return resultMap;
	}
	
	/**
	 * 查询首页楼层商品的动态价格
	 * @param request
	 * @return
	 */
	@RequestMapping("/listFloorProductPrice")
	@ResponseBody
	public List<ProductEntity> listFloorPorductPrice(HttpServletRequest request){
		Map<String, Object> param = new HashMap<String, Object>();
		String customerLevel = getCustomerLevel();
		String productIds = request.getParameter("productIds");
		List<ProductEntity> priceList = null;
		if(StringUtil.isNotEmpty(productIds)){
			List<String> productIdsList = new ArrayList<String>();
			for (String productId : productIds.split(",")) {
				productIdsList.add(productId);
			}
			param.put("customerLevel", customerLevel);
			param.put("productIdsList", productIdsList);
			param.put("isLogin", isLogin(request)?"1":"0");
			priceList= productService.listFoorProductPrice(param);
			productService.initProductDefaultSpecPrice(priceList);
		}
		return priceList;
	}
	
	
	
}
